package com.sunday.pinxinghui.widgets;

import android.content.Context;
import android.graphics.Color;
import android.text.Editable;
import android.text.SpannableString;
import android.text.Spanned;
import android.text.TextUtils;
import android.text.TextWatcher;
import android.text.style.RelativeSizeSpan;
import android.text.style.StyleSpan;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.ListView;
import android.widget.TextView;

import com.bumptech.glide.Glide;
import com.makeramen.roundedimageview.RoundedImageView;
import com.squareup.picasso.Picasso;
import com.sunday.common.adapter.CommenAdapter;
import com.sunday.common.adapter.ViewHolder;
import com.sunday.common.model.ResultDO;
import com.sunday.common.utils.PixUtils;
import com.sunday.common.utils.ToastUtils;
import com.sunday.common.widgets.MyWindow;
import com.sunday.pinxinghui.R;
import com.sunday.pinxinghui.base.BaseApplication;
import com.sunday.pinxinghui.entity.Member;
import com.sunday.pinxinghui.entity.Product;
import com.sunday.pinxinghui.entity.ProductDetail;
import com.sunday.pinxinghui.entity.ProductNormal;
import com.sunday.pinxinghui.entity.Spec;
import com.sunday.pinxinghui.network.ApiClient;


import java.math.RoundingMode;
import java.util.List;

import butterknife.Bind;
import butterknife.ButterKnife;
import butterknife.OnClick;
import retrofit2.Call;
import retrofit2.Callback;
import retrofit2.Response;


/**
 * Created by 刘涛 on 2017/8/27.
 */

public class ProductWindow extends MyWindow {

    private View contentView;

    private int num = 1;
    @Bind(R.id.list_view)
    ListView listView;
    @Bind(R.id.image_view)
    RoundedImageView imageView;
    @Bind(R.id.price)
    TextView price;
    @Bind(R.id.store)
    TextView store;
    @Bind(R.id.num)
    TextView numT;
    @Bind(R.id.btn_cart)
    TextView btn_cart;
    @Bind(R.id.btn_buy)
    TextView btn_buy;
    @Bind(R.id.minus)
    View minus;
    @Bind(R.id.add)
    View add;
    @Bind(R.id.spec_selected)
    TextView specSelected;
    @Bind(R.id.btn_cancel)
    ImageView btnCancel;

    private Context mContext;
    private int maxCount;

    private ProductDetail product;
    private Click click;
    private Integer normalId = null;
    private BaseAdapter baseAdapter;
    private Member member;


    public ProductWindow(Context context, ProductDetail productDetail, Click click) {
        super(context);
        this.product = productDetail;
        mContext = context;
        this.click = click;

        LayoutInflater mLayoutInflater = LayoutInflater.from(context);
        contentView = mLayoutInflater.inflate(R.layout.window_product, null);

        setContentView(contentView);
        ButterKnife.bind(this, contentView);

        imageView.setCornerRadius(2.5f);
        member = BaseApplication.getInstance().getMember();

        if (product.getNormals() != null && product.getNormals().size() > 0) {
            value = new String[product.getNormals().size()];
            for (int i = 0; i < product.getNormals().size(); i++) {
                Spec normalsBean = product.getNormals().get(i);
                if (normalsBean.getNormses() != null && normalsBean.getNormses().size() > 0) {
                    value[i] = normalsBean.getNormses().get(0).getValueId();
                }
            }

            getData(getValue());
            baseAdapter = new BaseAdapter(context, product.getNormals(), R.layout.item_window_product);
            listView.setAdapter(baseAdapter);

            if (TextUtils.isEmpty(product.getImage())) {
                product.setImage("http");
            }
            Glide.with(context).load(product.getImage()).placeholder(R.mipmap.ic_default).into(imageView);


            String mprice = String.format("¥%s", product.getSalePrice().setScale(2, RoundingMode.HALF_UP));

            SpannableString msp = new SpannableString(mprice);
            //msp.setSpan(new RelativeSizeSpan(1.5f), 1, mprice.length() - 3, Spanned.SPAN_EXCLUSIVE_EXCLUSIVE);  //2.0f表示默认字体大小的两倍
            // msp.setSpan(new StyleSpan(android.graphics.Typeface.BOLD), 1, mprice.length() - 3, Spanned.SPAN_EXCLUSIVE_EXCLUSIVE);  //粗体
            price.setText(msp);

            maxCount = product.getStore();

            store.setText(String.format("库存%d%s", maxCount, "件"));

            add.setVisibility(View.VISIBLE);
            minus.setVisibility(View.VISIBLE);
        }


    }


    public void show(View view, int type, int productType) {
        //type 1 加入购物车 2 立即购买
        btn_buy.setVisibility(type != 1 ? View.VISIBLE : View.GONE);
        btn_cart.setVisibility(type != 2 ? View.VISIBLE : View.GONE);
        show(view);
    }

    @OnClick(R.id.btn_cart)
    void btnCart() {
        if (product.getType() == 3 && product.getStatus() == 1) {
            ToastUtils.showToast(mContext, "活动暂未开始");
            return;
        }
        if (click != null) {
            click.click(normalId, num, 1);
            dismiss();
        }
    }

    @OnClick(R.id.btn_buy)
    void btnBuy() {
        if (product.getType() == 3 && product.getStatus() == 1) {
            ToastUtils.showToast(mContext, "活动暂未开始");
            return;
        }
        if (click != null) {
            click.click(normalId, num, 2);
            dismiss();
        }
    }

    @OnClick(R.id.add)
    void add() {
        if (num >= maxCount) {
            return;
        }
        num++;
        numT.setText(num + "");
    }

    @OnClick(R.id.minus)
    void minus() {
        if (num <= 1) {
            return;
        }
        num--;
        numT.setText(num + "");
    }


    @OnClick(R.id.btn_cancel)
    void cancel() {
        this.dismiss();
    }

    private class BaseAdapter extends CommenAdapter {

        public BaseAdapter(Context context, List mDatas, int itemLayoutId) {
            super(context, mDatas, itemLayoutId);
        }

        @Override
        public void convert(ViewHolder helper, Object item, int position) {
            TextView name = helper.getView(R.id.name);
            Spec normalsBean = (Spec) item;
            name.setText(normalsBean.getKey());

            com.sunday.pinxinghui.widgets.FlowLayout flowLayout = helper.getView(R.id.flow_layout);

            flowLayout.removeAllViews();
            int i = 0;


            for (Spec.NormsesBean normsesBean : normalsBean.getNormses()) {

                View view = LayoutInflater.from(mContext).inflate(R.layout.item_item_window_product, null);
                int ranHeight = PixUtils.dip2px(mContext, 30);
                ViewGroup.MarginLayoutParams lp = new ViewGroup.MarginLayoutParams(PixUtils.dip2px(mContext, ViewGroup.LayoutParams.WRAP_CONTENT), ranHeight);
                lp.setMargins(10, 0, 10, 20);

                TextView tv = ButterKnife.findById(view, R.id.name);
                View.OnClickListener onClickListener = new View.OnClickListener() {
                    @Override
                    public void onClick(View v) {
                        Spec.NormsesBean normsesBean = (Spec.NormsesBean) v.getTag();
                        int position = (int) v.getTag(R.id.name);
                        value[position] = normsesBean.getValueId();
                        baseAdapter.notifyDataSetChanged();
                        getData(getValue());

                    }
                };
                tv.setSelected(value[position].equals(normsesBean.getValueId()));
                tv.setText(normsesBean.getValue());
                tv.setTag(R.id.name, position);
                tv.setTag(normsesBean);
                tv.setOnClickListener(onClickListener);
                flowLayout.addView(view, lp);
                i++;
            }

        }
    }



    private String value[];


    private void getData(String valueIds) {
        if (TextUtils.isEmpty(valueIds)) {
            return;
        }
        Call<ResultDO<ProductNormal>> call = ApiClient.getApiAdapter().getNormal(product.getProductId(), valueIds, member.getId());
        call.enqueue(new Callback<ResultDO<ProductNormal>>() {
            @Override
            public void onResponse(Call<ResultDO<ProductNormal>> call, Response<ResultDO<ProductNormal>> response) {
                if (response.body() == null) {
                    return;
                }
                if (response.body().getCode() == 0 && response.body().getResult() != null) {
                    ProductNormal productNormal = response.body().getResult();
                    String mprice = "";
                    switch (product.getType()) {
                        case 1:
                            //普通
                            if (member.getIsVip() == 1) {
                                mprice = String.format("¥%s", productNormal.getVipPriceView().setScale(2, RoundingMode.HALF_UP));
                            } else {
                                mprice = String.format("¥%s", productNormal.getSalePriceView().setScale(2, RoundingMode.HALF_UP));
                            }
                            break;
                        case 2:
                            //秒杀
                            mprice = String.format("¥%s", productNormal.getLimitCountPriceView().setScale(2, RoundingMode.HALF_UP));
                            break;
                        case 3:
                            //限时购
                            if (product.getStatus() == 3) {
                                mprice = String.format("¥%s", productNormal.getLimitPriceView().setScale(2, RoundingMode.HALF_UP));
                            } else {
                                if (member.getIsVip() == 1) {
                                    mprice = String.format("¥%s", productNormal.getVipPriceView().setScale(2, RoundingMode.HALF_UP));
                                } else {
                                    mprice = String.format("¥%s", productNormal.getSalePriceView().setScale(2, RoundingMode.HALF_UP));
                                }
                            }
                            break;
                    }


                    SpannableString msp = new SpannableString(mprice);
                    //msp.setSpan(new RelativeSizeSpan(1.5f), 1, mprice.length() - 3, Spanned.SPAN_EXCLUSIVE_EXCLUSIVE);  //2.0f表示默认字体大小的两倍
                    //msp.setSpan(new StyleSpan(android.graphics.Typeface.BOLD), 1, mprice.length() - 3, Spanned.SPAN_EXCLUSIVE_EXCLUSIVE);  //粗体
                    price.setText(msp);
                    store.setText(String.format("库存%d%s", productNormal.getStore(), "件"));
                    specSelected.setText("已选择：" + productNormal.getValues());

                    if (!TextUtils.isEmpty(productNormal.getImage())) {
                        Glide.with(mContext).load(productNormal.getImage()).placeholder(R.mipmap.ic_default).into(imageView);
                    }

                    normalId = productNormal.getId();
                    maxCount = productNormal.getStore();

                    if (num > maxCount && num != 1) {
                        num = maxCount;
                        numT.setText(num + "");
                    }

                }
            }

            @Override
            public void onFailure(Call<ResultDO<ProductNormal>> call, Throwable t) {

            }
        });
    }


    private String getValue() {
        String VALUE = "";
        for (int i = 0; i < value.length; i++) {
            if (TextUtils.isEmpty(VALUE)) {
                VALUE = value[i];
            } else {
                VALUE = VALUE + "," + value[i];
            }
        }
        return VALUE;
    }


    public interface Click {
        public void click(Integer normalId, int num, int type);
    }
}
